package cn.modoumama.utils;

import cn.modoumama.dto.ColumnInfoDto;
import cn.modoumama.dto.GDAOBeanDetailInfoDto;
import cn.modoumama.dto.GDAODetailInfoDto;
import org.apache.commons.lang.StringUtils;

import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.*;
import java.util.*;

@SuppressWarnings({"rawtypes", "unchecked"})
public class GDAOToolsUtil {

    public static String getListDataByIndex(List<String> list, int index) {
        if (list != null && list.size() > index) {
            return list.get(index);
        }
        return "";
    }

    /**
     * @param list
     * @param packageNameList
     * @param type            1:model   2:dao   3:daoImpl
     * @return
     */
    public static String getJavaImportPart(List<String> list, List<String> packageNameList, List<String> basePackageList) {

        StringBuffer buffer = new StringBuffer();
        if (list != null && list.size() > 0) {
            buffer.append(list.get(0));
        }

        if (packageNameList != null) {
            for (String packageName : packageNameList) {
                if (!buffer.toString().contains(packageName)) {
                    buffer.append("import " + packageName + ";" + GDAOToolsConst.PRINT_LINE);
                }
            }
        }

        for (String packageName : basePackageList) {
            if (!buffer.toString().contains(packageName)) {
                buffer.append("import " + packageName + ";" + GDAOToolsConst.PRINT_LINE);
            }
        }

        return buffer.toString();
    }


    /**
     * 获取db连接
     *
     * @param configProperties
     * @return
     * @throws Exception
     */
    public static Connection getConnection(String subLibPrex, Properties configProperties)
            throws Exception {
        String db_driver = configProperties.getProperty(subLibPrex + "DB_DRIVER");
        String db_url = configProperties.getProperty(subLibPrex + "DB_URL");
        String db_user = configProperties.getProperty(subLibPrex + "DB_USER");
        String db_password = configProperties.getProperty(subLibPrex + "DB_PASSWORD");
        try {
            Class.forName(db_driver);
            return DriverManager.getConnection(db_url, db_user, db_password);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 读取配置文件propertiesFilePath
     *
     * @param propertiesFilePath
     * @return
     * @throws Exception
     */
    public static Properties readProperties(String propertiesFilePath)
            throws Exception {
        Properties properties = new Properties();
        FileInputStream inStream = null;
        try {
            inStream = new FileInputStream(propertiesFilePath);
            properties.load(inStream);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return properties;
    }

    /**
     * 读取流inputStream的信息
     *
     * @param inputStream
     * @return
     * @throws Exception
     */
    public static Properties readPropertiesByInputStream(InputStream inputStream)
            throws Exception {
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return properties;

    }

    /**
     * 判断字符串str是否为空
     *
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        return str == null || str.trim().length() == 0;
    }

    /**
     * 获取生成DAO的详细信息 （字段，属性，类型）
     *
     * @param conn
     * @param tableName
     * @param sqlTypeProperties
     * @return
     * @throws Exception
     */
    public static GDAODetailInfoDto getGDAODetailInfo(Connection conn, String tableName, Properties sqlTypeProperties, String dbSchema) throws Exception {

        GDAODetailInfoDto detailInfoDto = new GDAODetailInfoDto();
        detailInfoDto.setTableName(tableName);
        detailInfoDto.setClassName(getClassName(tableName));

        String seqIdName = null;
        detailInfoDto.setSeqIdName(seqIdName);

        Statement statement = conn.createStatement();

        //获取表注释，设置类描述
        String getTableCommentSQL = "select  TABLE_COMMENT from information_schema.tables where table_schema ='" + dbSchema + "'  and table_name ='" + tableName.toUpperCase() + "'";
        ResultSet tableComment = statement.executeQuery(getTableCommentSQL);
        while (tableComment.next()) {
            detailInfoDto.setTableComment(tableComment.getString("TABLE_COMMENT"));
            break;
        }


        String getTableColumnSQL = "select  column_name, column_comment from information_schema.columns where table_schema ='" + dbSchema + "'  and table_name ='" + tableName.toUpperCase() + "'";
        ResultSet resultSet1 = statement.executeQuery(getTableColumnSQL);
        Map commentMap = new HashMap();
        while (resultSet1.next()) {

            commentMap.put(resultSet1.getString("column_name"), resultSet1.getString("column_comment"));
        }

        String execSqlPk = "SELECT  DISTINCT c.COLUMN_NAME  FROM  INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS t,  INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS c WHERE  t.TABLE_NAME = c.TABLE_NAME  AND t.TABLE_SCHEMA = '" + dbSchema + "'  AND t.CONSTRAINT_TYPE = 'PRIMARY KEY' AND t.TABLE_NAME = '" + tableName.toUpperCase() + "'";
        ResultSet resultSetPk = statement.executeQuery(execSqlPk);
        StringBuffer pk = new StringBuffer();
        while (resultSetPk.next()) {
            if (pk.length() > 0) {
                pk.append(",");
            }
            pk.append("\"" + getPropertyName(resultSetPk.getString(1)) + "\"");
        }

        detailInfoDto.setPkList(pk.toString());

        String executeSql = "select * from " + tableName;

        ResultSet resultSet = statement.executeQuery(executeSql);

        ResultSetMetaData metaData = resultSet.getMetaData();
        for (int i = 1; i <= metaData.getColumnCount(); i++) {
            //被标记为删除的字段忽视
            if (metaData.getColumnName(i).toLowerCase().startsWith("d_")) {
                continue;
            }

            ColumnInfoDto columnIDto = new ColumnInfoDto();
            columnIDto.setColumnName(metaData.getColumnName(i));
            columnIDto.setPropertyName(getPropertyName(metaData.getColumnName(i)));
            columnIDto.setColumnComment((String) commentMap.get(columnIDto.getColumnName()));
            System.out.println(metaData.getColumnType(i) + "------------------");
            if (metaData.getColumnType(i) == 2) {
                //System.out.println(tableName + " : " + columnIDto.getColumnName() + " : " + metaData.getScale(i) + " : " + metaData.getPrecision(i));
                if (metaData.getScale(i) > 0) {
                    columnIDto.setSqlType(6);
                    columnIDto.setJavaType(getColumnMethod(sqlTypeProperties, 6));
                } else if (metaData.getPrecision(i) > 10) {
                    columnIDto.setSqlType(-5);
                    columnIDto.setJavaType(getColumnMethod(sqlTypeProperties, -5));
                } else {
                    columnIDto.setSqlType(4);
                    columnIDto.setJavaType(getColumnMethod(sqlTypeProperties, 4));
                }
            } else {
                columnIDto.setSqlType(metaData.getColumnType(i));
                columnIDto.setJavaType(getColumnMethod(sqlTypeProperties, metaData.getColumnType(i)));
            }

            detailInfoDto.getColumnList().add(columnIDto);
            String className = getColumnClassName(sqlTypeProperties, columnIDto.getSqlType());
            if (!detailInfoDto.getPackageNameList().contains(className) && !className.contains("lang")) {
                detailInfoDto.getPackageNameList().add(className);
            }
        }

        return detailInfoDto;

    }


    /**
     * 根据列名获取属性名
     *
     * @param columnName
     * @return
     */
    public static String getPropertyName(String columnName) {
        StringBuffer propertyName = new StringBuffer();
        columnName = columnName.toLowerCase();

        String[] array = columnName.split("_");

//		propertyName += array[0];
        propertyName.append(array[0]);

        for (int i = 1; i < array.length; i++) {
            if (StringUtils.isEmpty(array[i])) {
                continue;
            }
//			propertyName += array[i].substring(0, 1).toUpperCase() + array[i].substring(1);
            propertyName.append(array[i].substring(0, 1).toUpperCase()).append(array[i].substring(1));
        }
        return propertyName.toString();
    }

    /**
     * 根据表名获取类名
     *
     * @param tableName
     * @return
     */
    public static String getClassName(String tableName) {
        StringBuffer propertyName = new StringBuffer();
        tableName = tableName.toLowerCase();

        String[] array = tableName.split("_");

        for (int i = 0; i < array.length; i++) {
//			propertyName += array[i].substring(0, 1).toUpperCase() + array[i].substring(1);
            propertyName.append(array[i].substring(0, 1).toUpperCase()).append(array[i].substring(1));
        }
        return propertyName.toString();
    }

    /**
     * 获取列对应java的类名（包名 + 类名）
     *
     * @param sqlTypeProperties
     * @param type
     * @return
     */
    public static String getColumnClassName(Properties sqlTypeProperties, int type) {

        String columnClassName = "";

        Iterator iterator = sqlTypeProperties.keySet().iterator();

        String key = null;
        while (iterator.hasNext()) {
            key = (String) iterator.next();

            if (String.valueOf(type).equals(key)) {
                String value = sqlTypeProperties.getProperty(key);

                String[] arrayStr = value.split(",");

                if (arrayStr != null && arrayStr.length > 1) {
                    if (arrayStr[1].indexOf(".") != -1) {
                        columnClassName = arrayStr[1].trim();
                    }
                }
                break;
            }
        }

        return columnClassName;

    }

    /**
     * 获取列对应java的类名（类名）
     *
     * @param sqlTypeProperties
     * @param type
     * @return
     */
    public static String getColumnMethod(Properties sqlTypeProperties, int type) {

        String columnMethod = null;

        Iterator iterator = sqlTypeProperties.keySet().iterator();

        String key = null;
        while (iterator.hasNext()) {
            key = (String) iterator.next();

            if (String.valueOf(type).equals(key)) {
                String value = sqlTypeProperties.getProperty(key);

                String[] arrayStr = value.split(",");

                if (arrayStr != null && arrayStr.length > 0) {
                    columnMethod = arrayStr[0].trim();
                }
                break;
            }
        }

        if (isEmpty(columnMethod)) {
            columnMethod = "String";
        }

        return columnMethod;

    }

    public static List<GDAODetailInfoDto> getNewDAOInfo(List<GDAOBeanDetailInfoDto> gdaoBeanDetailInfoList, List<GDAODetailInfoDto> gdaoDetailInfoList) {

        List<GDAODetailInfoDto> detailInfoDtoList = new ArrayList<GDAODetailInfoDto>();
        for (GDAODetailInfoDto detailInfoDto : gdaoDetailInfoList) {

            if (gdaoBeanDetailInfoList == null || gdaoBeanDetailInfoList.size() == 0) {
                detailInfoDtoList.add(detailInfoDto);
                continue;
            }
            for (int i = 0; i < gdaoBeanDetailInfoList.size(); i++) {
                if ((detailInfoDto.getBeanName() + "BaseDao").equals(gdaoBeanDetailInfoList.get(i).getId())) {
                    break;
                }
                if (i == gdaoBeanDetailInfoList.size() - 1) {
                    detailInfoDtoList.add(detailInfoDto);
                }
            }
        }

        return detailInfoDtoList;
    }

    public static List<GDAODetailInfoDto> getNewSqlMapConfigInfoList(List<String> sqlMapConfigInfoList, List<GDAODetailInfoDto> gdaoDetailInfoList) {

        List<GDAODetailInfoDto> detailInfoDtoList = new ArrayList<GDAODetailInfoDto>();
        for (GDAODetailInfoDto detailInfoDto : gdaoDetailInfoList) {

            if (sqlMapConfigInfoList == null || sqlMapConfigInfoList.size() == 0) {
                detailInfoDtoList.add(detailInfoDto);
                continue;
            }

            for (int i = 0; i < sqlMapConfigInfoList.size(); i++) {
                if (("dao/sqlmap_base_" + detailInfoDto.getBeanName() + ".xml").equals(sqlMapConfigInfoList.get(i).toString())) {
                    break;
                }
                if (i == sqlMapConfigInfoList.size() - 1) {
                    detailInfoDtoList.add(detailInfoDto);
                }
            }
        }

        return detailInfoDtoList;
    }


}
